package proj2501.simple_module;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import javax.xml.bind.JAXB;

import proj2501.util.UU;

class P009JAXB {
	public P009JAXB() {
		System.out.println("JAXB (Java Architecture for XML Binding)");
		ClassA.ClassAJaxb jaxb1 = new ClassA().getJaxb();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		JAXB.marshal(jaxb1, baos);
		String xml;
		try {
			xml = baos.toString("UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException();
		}
		System.out.println(xml);
//		String path = "test01.xml"; 
//		UU.write(path, xml);
		String xml2;
//		xml2 = UU.read(path);
		xml2 = xml;
		ClassA.ClassAJaxb jaxb2 = JAXB.unmarshal(new StringReader(xml2), ClassA.ClassAJaxb.class);
		jaxb2.a += 990000;
		ClassA classA = new ClassA();
		classA.setJaxb(jaxb2);
		JAXB.marshal(classA.getJaxb(), System.out);
	}
	public static class ClassA {
		private int a;
		private int b;
		private String s1;
		private String s2;
		private int[] array;
		private byte[] bytes;
		private List<String> list;
		private ClassB classB;
		public ClassA() {
			a = 123;
			s2 = "日本語\n改行あり";
			array = new int[] {1, 3, 2};
			try {
				bytes = "any carnal pleasure.".getBytes(UU.getUTF_8Name()); // Words from Wikipedia - Base64.
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException();
			}
			list = new LinkedList<String>();
			list.add("str1");
			list.add("str2");
			classB = new ClassB();
		}
		
		public static class ClassAJaxb {
			public int a;
			public int b;
			public String s1;
			public String s2;
			public int[] array;
			public byte[] bytes;
			public List<String> list;
			public ClassB.ClassBJaxb classBJaxb;
		}
		public ClassAJaxb getJaxb() {
			ClassAJaxb obj = new ClassAJaxb();
			obj.a = a;
			obj.b = b;
			obj.s1 = s1;
			obj.s2 = s2;
			obj.array = array;
			obj.bytes = bytes;
			obj.list = list;
			obj.classBJaxb = classB.getJaxb();
			return obj;
		}
		public void setJaxb(ClassAJaxb obj) {
			a = obj.a;
			b = obj.b;
			s1 = obj.s1;
			s2 = obj.s2;
			array = obj.array;
			bytes = obj.bytes;
			list = obj.list;
			classB = new ClassB();
			classB.setJaxb(obj.classBJaxb);
		}
	}
	public static class ClassB {
		private String string = "Random Double: ";
		{
			string += new Random().nextDouble();
		}
		public static class ClassBJaxb {
			public String string;
		}
		public ClassBJaxb getJaxb() {
			ClassBJaxb obj = new ClassBJaxb();
			obj.string = string;
			return obj;
		}
		public void setJaxb(ClassBJaxb obj) {
			string = obj.string;
		}
	}
}
